package com.shenjinzheng.service.impl;

import cn.hutool.crypto.digest.BCrypt;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.shenjinzheng.dto.AdminLoginDTO;
import com.shenjinzheng.entity.Admin;
import com.shenjinzheng.mapper.AdminMapper;
import com.shenjinzheng.service.AdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.shenjinzheng.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.nio.charset.StandardCharsets;
import java.security.Key;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author shenjinzheng
 * @since 2024-10-08
 */
@Slf4j
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Resource
    private JwtUtil jwtUtil;
    @Override
    public String login(AdminLoginDTO adminLoginDTO) {
        log.info("加密后的密码:{}", BCrypt.hashpw(adminLoginDTO.getPassword()));
        //1-根据用户名,跟数据库进行比对
        LambdaQueryWrapper <Admin> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Admin::getUsername,adminLoginDTO.getUsername());
        Admin admin = this.getOne(wrapper);
        //3-如果没有,提示用户名或密码错误
        if (admin==null){
            throw new RuntimeException("用户名或密码错误");
        }
        if (!BCrypt.checkpw(adminLoginDTO.getPassword(),admin.getPassword())){
            throw new RuntimeException("用户名或密码错误");
        }
        Claims claims= Jwts.claims();
        claims.put("id","1");
        Key key= Keys.hmacShaKeyFor("12345689012345678901234567890123456890123456789012345678901234568901234567890123456789012345689012345678901234567890".getBytes(StandardCharsets.UTF_8));

        //2-如果有数据,生成token返回
        String token = jwtUtil.createToken(claims, key);
        //比对密码
        return token;
    }
}
